/**
 * Created by chenxq on 2018/1/3.
 */
import React,{Component} from 'react';
import { Table, Card, Button ,Form ,Input ,Row ,Col ,Select ,Popconfirm ,Modal ,message ,Divider,DatePicker,Radio,Dropdown,Menu,Icon} from 'antd';
import {connect} from 'dva';
import DescriptionList from '../../components/DescriptionList';
import {convertLongToString,findObjByKey} from '../../utils/index';
import {reg} from '../../utils/CheckList';
const { Description } = DescriptionList;
import {signStatus,payTypes} from '../defaultData';
import AccountList from '../../components/Sign/AccountList';
import AddAccount from '../../components/Sign/AddAccount';
import Assign from '../../components/Sign/Assign';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {Link} from 'dva/router';
import styles from '../TableList.less';
@connect(state=>({
  sign:state.sign,
  userManage:state.usermanagement,
  customer:state.customer,
  product:state.product
}))
@Form.create()
export default class extends Component{
  state={
    editable:false,
    tabKey:'info',
    visible:false,
    key:Math.random(),
    addAccountIsvisible:false,
    addKey:Math.random(),
    AddObj:{
      info:{},
      type:'income'
    },
  }

  getContent(){
    let {detail} = this.props.sign;
    return (
      <DescriptionList  size="small" col="2">
        <Description term="签单状态">{findObjByKey(signStatus,detail.state).name}</Description>
      </DescriptionList>
    )
  }

  getProductName=(proId)=>{
    let {product,userManage,sign} = this.props;
    let proList=product.allList || [];
    if(proId){
      let proObj= proList.find(item=>item.id==proId);
      if(proObj){
        return proObj.name;
      }
    }
    return '';
  }
  getUserName=(userId)=>{
    let {userManage,sign} = this.props;
    let list=userManage.allList || [];
    if(userId){
      let obj= list.find(item=>item.id==userId);
      if(obj){
        return obj.userName;
      }
    }
    return '';
  }
  getFormCell=()=>{
    let {product,userManage,sign} = this.props;
    let userList=userManage.allList || [];
    let userIdArr=userList.map(item=>item.id);
    let editObj=sign.detail;
    let handleValidator= function(rule,val,callback){
      if(!val){
        callback();
        return;
      }
      if(userIdArr.indexOf(val)>=0){
        callback();
      }else{
        callback('用户不存在')
      }
    }
    return [{
      label:'产品',
      key:'productId',
      component: <Select>
        {product.allList.map(item=>(<Option key={item.id} value={item.id}>{item.name}</Option>))}
      </Select>,
      field:{
        initialValue: editObj.productId || (product.allList[0] ? product.allList[0].id : null),
        rules:[{required:true,message:'请选择产品'}]},
      text: this.getProductName(editObj.productId)
    },{
      label:'批复额度',
      key:'replyQuotas',
      component: <Input placeholder="请输入批复额度" />,
      field:{
        initialValue: editObj.replyQuotas && (editObj.replyQuotas /100).toFixed(2) || '',
        rules:[{required:true,message:'请输入批复额度'},
          {pattern:reg.money,message:'输入格式不正确'}]
      },
      text: editObj.replyQuotas && (editObj.replyQuotas /100).toFixed(2) || ''
    },{
      label:'批复利息',
      key:'replyInterest',
      component: <Input placeholder="请输入批复利息" />,
      field:{
        initialValue: editObj.replyInterest && (editObj.replyInterest /100).toFixed(2) || '',
        rules:[{required:true,message:'请输入批复利息'},
          {pattern:reg.money,message:'输入格式不正确'}]
      },
    },{
      label:'批复周期',
      key:'replyPeriod',
      component: <Input placeholder="请输入批复周期" />,
      field:{
        rules:[{required:true,message:'请输入批复周期'}]
      }
    },{
      label:'支付方式',
      key:'payWay',
      component: <Select>
        {payTypes.map(item=>(<Option key={item.key} value={item.key}>{item.name}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.payWay || payTypes[0].key,
      },
      text: editObj.payWay ? findObjByKey(payTypes,editObj.payWay).name  :''
    },{
      label:'当前状态',
      key:'state',
      component: <Select>
        {signStatus.map(item=>(<Option key={item.key} value={item.key}>{item.name}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.state || signStatus[0].key,
      },
      text:editObj.state ? findObjByKey(signStatus,editObj.state).name :''
    },{
      label:'指派给',
      key:'assignedTo',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.assignedTo || '',
        rules:[{
          validator: handleValidator
        }]
      },
      text:this.getUserName(editObj.assignedTo)
    },{
      label:'产品成本',
      key:'cost',
      component: <Input placeholder="请输入产品成本" />,
      field:{
        initialValue: editObj.cost && (editObj.cost /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'定金',
      key:'downpayment',
      component: <Input placeholder="请输入定金" />,
      field:{
        initialValue: editObj.downpayment && (editObj.downpayment /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'征信费',
      key:'creditInvestigationFee',
      component: <Input placeholder="请输入征信费" />,
      field:{
        initialValue: editObj.creditInvestigationFee && (editObj.creditInvestigationFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'资料费',
      key:'infoFee',
      component: <Input placeholder="请输入资料费" />,
      field:{
        initialValue: editObj.infoFee && (editObj.infoFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'调查费',
      key:'investigateFee',
      component: <Input placeholder="请输入调查费" />,
      field:{
        initialValue: editObj.investigateFee && (editObj.investigateFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'合同约定费',
      key:'contractualFee',
      component: <Input placeholder="请输入合同约定费" />,
      field:{
        initialValue: editObj.contractualFee && (editObj.contractualFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'加收费用',
      key:'additionalFee',
      component: <Input placeholder="请输入加收费用" />,
      field:{
        initialValue: editObj.additionalFee && (editObj.additionalFee /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'是否押还款期数',
      key:'holdRepayment',
      component: <RadioGroup>
        <Radio value={false}>否</Radio>
        <Radio value={true}>是</Radio>
      </RadioGroup>,
      field:{
        initialValue: !!editObj.holdRepayment
      },
      text: !!editObj.holdRepayment? '是' :'否'
    },{
      label:'是否有返点',
      key:'rebate',
      component:<RadioGroup>
        <Radio value={false}>否</Radio>
        <Radio value={true}>是</Radio>
      </RadioGroup>,
      field:{
        initialValue: !!editObj.rebate
      },
      text: !!editObj.rebate ? '是' :'否'
    },{
      label:'返点金额',
      key:'rebateAmount',
      component: <Input placeholder="请输入返点金额" />,
      field:{
        initialValue: editObj.rebateAmount && (editObj.rebateAmount /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'应收总费用',
      key:'receivable',
      component: <Input placeholder="请输入应收总费用" />,
      field:{
        initialValue: editObj.receivable && (editObj.receivable /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'实收总费用',
      key:'netReceipt',
      component: <Input placeholder="请输入实收总费用" />,
      field:{
        initialValue: editObj.netReceipt && (editObj.netReceipt /100).toFixed(2) || '',
        rules:[
          {pattern:reg.money,message:'输入格式不正确'}]
      }
    },{
      label:'备注',
      key:'remark',
      span:24,
      formItemLayout : {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      component: <Input.TextArea  placeholder="请输入备注"  />
    },{
      label:'客户经理',
      key:'customerManager',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children"
      >
        {userList.map((item,index)=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.customerManager || '',
        rules:[{
          validator: handleValidator
        }]
      },
      text:this.getUserName(editObj.customerManager)
    },{
      label:'权证经理',
      key:'warrantManager',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.warrantManager || '',
        rules:[{
          validator: handleValidator
        }]
      },
      text:this.getUserName(editObj.warrantManager)
    },{
      label:'贷款经理',
      key:'loanManager',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.loanManager || '',
        rules:[{
          validator: handleValidator
        }]
      },
      text:this.getUserName(editObj.loanManager)
    },{
      label:'经手人',
      key:'brokerage',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.brokerage || '',
        rules:[{
          validator: handleValidator
        }]
      },
      text:this.getUserName(editObj.brokerage)
    },{
      label:'复合人',
      key:'reviewPerson',
      component: <Select mode="combobox"
                         placeholder="请选择"
                         optionFilterProp="children"
                         optionLabelProp="children">
        {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
      </Select>,
      field:{
        initialValue:editObj.reviewPerson || '',
        rules:[{
          validator: handleValidator
        }]
      },
      text:this.getUserName(editObj.reviewPerson)
    }]

  }
  submit=()=>{
    let _this=this;
    let {sign} = this.props;
    let {detail} = sign ;
    this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        let params={
          ...values
        };
        params.customerId=detail.customerId;
        if(params.replyQuotas){
          params.replyQuotas=params.replyQuotas *100
        }
        if(params.replyInterest){
          params.replyInterest=params.replyInterest *100
        }
        if(params.cost){
          params.cost=params.cost *100
        }
        if(params.downpayment){
          params.downpayment=params.downpayment *100
        }
        if(params.creditInvestigationFee){
          params.creditInvestigationFee=params.creditInvestigationFee *100
        }
        if(params.infoFee){
          params.infoFee=params.infoFee *100
        }
        if(params.investigateFee){
          params.investigateFee=params.investigateFee *100
        }
        if(params.contractualFee){
          params.contractualFee=params.contractualFee *100
        }
        if(params.additionalFee){
          params.additionalFee=params.additionalFee *100
        }
        if(params.rebateAmount){
          params.rebateAmount=params.rebateAmount *100
        }
        if(params.receivable){
          params.receivable=params.receivable *100
        }
        if(params.netReceipt){
          params.netReceipt=params.netReceipt *100
        }
        let editObj=Object.assign({},detail,params);
        this.props.dispatch({
          type:'sign/fetchEdit',
          payload:editObj
        }).then(jsonData=>{
          if(jsonData.result){
            message.success(`修改成功`,0.8,()=> {
              _this.getDetail();
              _this.setState({
                editable:false
              })
            })
          }else{
            message.error(jsonData.msg || '修改失败')
          }
        });
      }
    })

  }
  addAccount=(type)=>{
    let {detail} = this.props.sign;
    this.setState({
      AddObj:{
        info:{
          loanId:detail.id
        },
        type
      },
      addAccountIsvisible:true,
      addKey:Math.random()
    })
  }

  getDetail=()=>{
    let {params} = this.props.match;
    this.props.dispatch({
      type:'sign/fetchGetDetail',
      payload:params.id
    });
  }
  componentDidMount(){
    let {params} = this.props.match;
    if(!params.id){
      message.error('参数有误');
      return ;
    }
    this.getDetail();
    this.props.dispatch({
      type:'usermanagement/fetchAllList',
      payload:{}
    });
    this.props.dispatch({
      type:'product/fetchAllList',
      payload:'USING'
    })
  }
  toggleEditable=()=>{
    this.setState({
      editable:!this.state.editable
    })
  }
  getExtra=()=>{
    return <div>
      {this.state.editable ? <Button style={{marginRight:15}} type='primary' onClick={this.submit}>保存</Button> :
        <Button style={{marginRight:15}} type='primary' onClick={this.assign}>操作</Button>
      }
      <Button onClick={this.toggleEditable}>{this.state.editable?'取消':'编辑'}</Button>
    </div>
  }
  getExtraList=()=>{
    return <div>
      <Button style={{marginRight:15}} type='primary' onClick={this.addAccount.bind(this,'income')}>新增收入</Button>
      <Button type='primary' onClick={this.addAccount.bind(this,'cost')}>新增支出 </Button>
    </div>
  }
  onTabChange=(key)=>{
    this.setState({
      tabKey:key
    })
  }
  assign=()=>{
    this.setState({
      key:Math.random(),
      visible:true
    })
  }
  render(){
    let {detail} = this.props.sign;
    let _this=this;
    let {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (<PageHeaderLayout title={<Link to={`/customer/detail/${detail.customerId}`}>{detail.customerName || '客户姓名'}</Link>}
                              content={this.getContent()}
                              tabList={[{key: 'info', tab: '签单信息'},
                                {key: 'list',tab: '收支记录'}]}
                              onTabChange={this.onTabChange}
    >
      {this.state.tabKey=== 'info' ?<Card title="签单详情" extra={this.getExtra()}>
        <Form className={styles.modal}>
          <Row gutter={24}>
            {this.getFormCell().map((item)=>{
              return <Col span={item.span || 12} key={item.key}>
                <FormItem label={item.label} {...(item.formItemLayout || formItemLayout)} validateFirst={true}>
                  {getFieldDecorator(item.key,{
                    initialValue:detail[item.key] || '',
                    ...item.field
                  })(
                    _this.state.editable? item.component : <span>{item.text || (item.field && item.field.initialValue) || detail[item.key] || ''}</span>
                  )}
                </FormItem>
              </Col>
            })}
          </Row>
        </Form>
        <Assign visible={this.state.visible}
                key={this.state.key}
                signObj={detail}
                onCancel={()=>{
                  this.setState({
                    visible:false
                  })
                }}
                onSubmit={()=>{
                  this.setState({
                    visible:false
                  })
                  this.getDetail()
                }}
                />
      </Card> :
      <Card title="收支记录" extra={this.getExtraList()}>
        <AccountList type={2} loanId={detail.id}/>
        <AddAccount isvisible={this.state.addAccountIsvisible}
                    key={this.state.addKey}
                    {...this.state.AddObj}
                    onCancel={()=>{
                      this.setState({
                        addAccountIsvisible:false
                      })
                    }}
        ></AddAccount>
      </Card>
      }

    </PageHeaderLayout>)
  }
}
